package com.doubao.hardware.context;

import com.doubao.hardware.util.HardwareAuthUtils;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import jakarta.servlet.http.HttpServletRequest;

/**
 * 认证拦截器
 * 从请求中提取用户ID并设置到UserContext中
 */
@Component
@Slf4j
public class AuthInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        // 清理上下文，避免线程复用导致的用户信息混淆
        UserContext.clear();

        // 从请求中提取用户ID
        Long userId = HardwareAuthUtils.getUserIdFromRequest(request);
        if (userId != null) {
            // 设置到上下文中
            UserContext.setUserId(userId);
            log.debug("设置当前用户ID: {}", userId);
        }

        // 始终返回true，允许请求继续，具体接口可以自行判断是否需要用户认证
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        // 请求结束后清理上下文
        UserContext.clear();
    }
}